/**
 * 
 */
package actions.demo;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;

import service.OrderService;
import actions.AbstractPagedQueryAction;
import actions.CommonExcelExportAction;
import beans.AbstractPagedQuery;
import beans.orderdemo.OrderQuery;
import domain.Order;

/**
 * @author wuzh
 * 
 */
public class OrderMainAction extends AbstractPagedQueryAction {

    /**
     * 用于查询订单.
     */
    private OrderService orderService;

    /**
     * 日期输入格式.
     */
    private final DateFormat DATE_FAMAT = new SimpleDateFormat("yyyy-MM-dd",
            Locale.UK);

    /**
     * 构造分页查询对象并进行分页查询.
     * @param form action form
     * @param request http request
     * @param totalCount 记录总个数
     * @param pagerOffset 查询的起始纪录位置
     * @param itemsPerPage 每页多少条纪录
     * @return AbstractPagedQuery Query
     * @throws Exception any exception
     */
    @Override
    public AbstractPagedQuery<Order> doPagedQuery(ActionForm form,
            HttpServletRequest request, int totalCount, int pagerOffset,
            int itemsPerPage) throws Exception {

        DynaValidatorForm queryCondForm = (DynaValidatorForm) form;
        OrderQuery myQuery = new OrderQuery();
        // 设置查询的分页参数
        myQuery.setItemsPerPage(itemsPerPage);
        myQuery.setTotalCount(totalCount);
        myQuery.setPagerOffset(pagerOffset);

        // 解析查询的条件
        String startdate = queryCondForm.getString("qStartTime");
        String stopdate = queryCondForm.getString("qEndTime");
        String productName = queryCondForm.getString("qProductName");
        if (null != startdate && !"".equals(startdate)) {
            myQuery.setStartTime(DATE_FAMAT.parse(startdate));
        }
        if (null != stopdate && !"".equals(stopdate)) {
            myQuery.setStopTime(DATE_FAMAT.parse(stopdate));
        }
        if (null != productName && !"".equals(productName)) {
            // 模糊查询
            myQuery.setProductName("%" + productName + "%");
        }

        // 调用OrderService进行分页查询
        orderService.queryOrders(myQuery);
        return myQuery;
    }

    /**
     * 批量删除订单.
     * @param mapping mapping
     * @param form v
     * @param request
     * @param response
     * @return action forward
     * @throws Exception
     */
    public ActionForward batchDelete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String[] ids = request.getParameterValues("ids");
        if (ids != null && !(ids.length == 0)) {
            Integer[] intIds = new Integer[ids.length];

            for (int i = 0; i < ids.length; i++) {
                intIds[i] = Integer.parseInt(ids[i]);
            }
            orderService.delOrderByIDs(intIds);
        }
        return mapping.findForward("main");
    }

    /**
     * 显示新增界面.
     * @param mapping struts mapping
     * @param form struts form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any execption
     */
    public ActionForward displayOrderCreateScreen(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        // 产生并保存Token,防止重复提交
        saveToken(request);
        // 初始化输入框
        DynaValidatorForm orderForm = (DynaValidatorForm) mapping
                .getModuleConfig().findFormBeanConfig("orderForm")
                .createActionForm(servlet);
        orderForm.set("productName", "");
        orderForm.set("customerName", "");
        orderForm.set("totalPrice", "");
        orderForm.set("orderDate", "");

        // 将Struts form 设置到request中
        request.setAttribute("orderForm", orderForm);
        return mapping.findForward("OrderCreate.screen");

    }

    /**
     * 显示更新操作.
     * @param mapping struts mapping
     * @param form struts form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any execption
     */
    public ActionForward displayOrderUpdateScreen(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        Order order = orderService.getOrderById(Integer.parseInt(id));
        if (order == null) {
            ActionMessages errMsgs = new ActionMessages();
            errMsgs.add("", new ActionMessage("errors.noSuchOrder"));
            this.saveErrors(request, errMsgs);
            return mapping.findForward("error.back");
        } else {
            DynaValidatorForm orderForm = (DynaValidatorForm) mapping
                    .getModuleConfig().findFormBeanConfig("orderForm")
                    .createActionForm(servlet);
            orderForm.set("id", order.getId().toString());
            orderForm.set("productName", order.getProductName());
            orderForm.set("customerName", order.getCustomerName());
            orderForm.set("totalPrice", order.getTotalPrice().toString());
            orderForm.set("orderDate", DATE_FAMAT.format(order.getOrderDate()));
            // 将Struts form 设置到request中
            request.setAttribute("orderForm", orderForm);
            // 设置token 防止重复提交
            this.saveToken(request);
            return mapping.findForward("OrderUpdate.screen");
        }
    }

    protected ActionForward doDataExport(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response, AbstractPagedQuery<?> pagedQuery)
            throws Exception {
        String templateFileName = Thread.currentThread()
                .getContextClassLoader().getResource("order-template.xls")
                .getFile();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("orders", pagedQuery.getQueryResults());
        dataMap.put("date", "2008年3季度");
        request.setAttribute(CommonExcelExportAction.EXCEL_TEMPLATE_NAME,
                templateFileName);
        request.setAttribute(CommonExcelExportAction.EXCEL_FILE_NAME,
                "订单列表.xls");
        request.setAttribute(CommonExcelExportAction.EXCEL_DATAMAP_NAME,
                dataMap);
        // 自动合并产品名称的单元格
        short[] mergedColumns = new short[] { (short) 0 };
        request.setAttribute(CommonExcelExportAction.EXCEL_AUTOMERGECOLUMNS,
                mergedColumns);

        request.getRequestDispatcher("CommonExcelExportAction.do").forward(
                request, response);
        return null;
    }

    /**
     * @param pOrderService the orderService to set
     */
    public void setOrderService(OrderService pOrderService) {
        orderService = pOrderService;
    }

}
